var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var expressEession = require('express-session');
var logger = require('morgan');
// var createError = require('http-errors');
// var router = express.Router();
// var http = require("http");
// var https = require("https");
var fs = require("fs");
// const multiparty = require('multiparty')

//引用artTemplate模块
// var template = require("art-template");
var ejs = require("ejs");
//引入body-parser   post传值要是用第三方中间件body-parser
var bodyparser = require('body-parser');

global.querystring = require('querystring');
global.mysql = require('mysql');
global.pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'root',
    port: 3306,
    database: 'guanglian',
    charset: 'UTF8MB4_BIN',
    timezone: "SYSTEM"
});
global.admin = '0';
global.com = require('./public/javascripts/common.js');
common = com.common;

//后台
var adminRouter = require('./routes/admin');
var productRouter = require('./routes/admin/product/product');
var productCategoryRouter = require('./routes/admin/product/product_category');
var carouselImagesRouter = require('./routes/admin/carousel_images/carousel_images');
var adminNavRouter = require('./routes/admin/admin_nav/admin_nav');
var fileUploadRouter = require('./routes/file_upload');
var announcementRouter = require('./routes/admin/news/announcement/announcement');
var recruitmentRouter = require('./routes/admin/recruitment/recruitment');
var applyRouter = require('./routes/admin/apply/apply');
var storeAddressRouter = require('./routes/admin/store_address/store_address');
var newsActivitiesRouter = require('./routes/admin/news/news_activities/news_activities');
//前台
var shelleyRouter = require('./routes/guanglian');
var app = express();

app.set('views', path.join(__dirname, 'views'));
// var template = require('art-template');
// template.config('base', '');
// template.config('extname', '.html');
app.engine('.html', ejs.__express);
app.set('view engine', 'html');


app.use(bodyparser.urlencoded({extended: false}));
app.use(bodyparser.json());

app.use(cookieParser());//这里要加()
// 使用 session 中间件
app.use(expressEession({
    secret: 'spflinux', // 对session id 相关的cookie 进行签名
    name: 'admin',
    resave: true,
    saveUninitialized: false, // 是否保存未初始化的会话
    cookie: {
        maxAge: 24 * 60 * 60 * 1000, // 设置 session 的有效时间，单位毫秒
        activeDuration: 5 * 60 * 1000, //激活时间，比如设置为30分钟，那么只要30分钟内用户有服务器的交互，那么就会被重新激活。
    },

}));



//应用级中间件  设置请求头  处理cros跨域
app.use((req, res, next) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    next();
})

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
// 后台管理路由
app.use('/admin', adminRouter);
app.use('/admin', productRouter);
app.use('/admin', productRouter);
app.use('/admin', productCategoryRouter);
app.use('/admin', carouselImagesRouter);
app.use('/admin', adminNavRouter);
app.use('/admin', fileUploadRouter);
app.use('/admin', announcementRouter);
app.use('/admin', recruitmentRouter);
app.use('/admin', applyRouter);
app.use('/admin', newsActivitiesRouter);
app.use('/admin', storeAddressRouter);

//前台路由
app.use('/', shelleyRouter);

/* 登录拦截 */
app.use((req, res, next) => {
    let url = req.originalUrl
    if (url !== "/admin" && !req.session.username) {
        return res.redirect("/admin");
    }else {
        next();
    }

})

var documentRoot = './public';
app.get('/', function (req, res) {
    var url = req.url;
    var file = documentRoot + url;
    fs.readFile(file, function (err, data) {
        if (err) {
            res.send('Welcome to Use Express!');
            /*res.writeHeader(404,{
                'content-type' : 'text/html;charset="utf-8"'
            });
            res.write('<h1>404错误</h1><p>你要找的页面不存在</p>');
            res.end();*/
        } else {
            res.writeHeader(200, {
                'content-type': 'text/html;charset="utf-8"'
            });
            res.write(data);
            res.end();
        }
    });
})
// var server=http.createServer(app).listen(8080, function () {
//   var host = server.address().address
//   var port = server.address().port
//   console.log("listen"+host+":"+port+" Success!")
// });


module.exports = app;
